package com.aim.questionnaire.service;

import com.aim.questionnaire.common.utils.DateUtil;
import com.aim.questionnaire.common.utils.MailUtil;
import com.aim.questionnaire.common.utils.UUIDUtil;
import com.aim.questionnaire.config.cors.ShortMessageConfig;
import com.aim.questionnaire.dao.ProjectEntityMapper;
import com.aim.questionnaire.dao.QuestionnaireEntityMapper;
import com.aim.questionnaire.dao.UserEntityMapper;
import com.aim.questionnaire.dao.entity.ProjectEntity;
import com.aim.questionnaire.dao.entity.QuestionnaireEntity;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by wln on 2018\8\6 0006.
 */
@Service
public class QuestionnaireService {

  @Autowired
  private QuestionnaireEntityMapper questionnaireEntityMapper;
  @Autowired
  private ProjectEntityMapper projectEntityMapper;
  @Autowired
  private UserEntityMapper userEntityMapper;

  /**
   * 根据项目id查询问卷列表
   *
   * @param map
   * @return
   */
  public List<Map<String, Object>> queryQuestionnaireListById(Map<String, Object> map) {
    String projectid = projectEntityMapper.selectProjectIdByName(map.get("projectName").toString());
    map.put("projectId", projectid);
    List<Map<String, Object>> resultList = questionnaireEntityMapper.queryQuestionListByProjectId(map);
    return resultList;
  }

  /**
   * 添加问卷
   *
   * @param map
   * @return 0:问卷名称已经存在 1:添加成功
   */
  public int addQuestionnaireInfo(Map<String, Object> map) {
    //判断问卷名称是否存在
    if (map.get("questionName") != null) {
      int userResult = questionnaireEntityMapper.queryExistQuestionnaire(map);
      if (userResult != 0) {
        //问卷名称已经存在
        return 0;
      }
    }
    //生成新问卷id
    String id = UUIDUtil.getOneUUID();
    map.put("id", id);
    //添加问卷题目信息
    if(map.get("questionId") != null){
      String preId = map.get("questionId").toString();
      Map<String, Object> preMap = questionnaireEntityMapper.queryQuestionnaireQuestionById(preId);
      if (preMap != null) {
        map.put("questionList", preMap.get("question"));
        map.put("questionTitle", preMap.get("questionTitle"));
      }
    }
    //创建时间
    Date date = DateUtil.getCreateTime();
    map.put("creationDate", date);
    map.put("lastUpdateDate", date);
    //创建人
    map.put("createdBy", map.get("user"));
    //修改人
    map.put("lastUpdatedBy", map.get("user"));
    //前台传入的时间戳转换
    String startTimeStr = map.get("startTime").toString();
    String endTimeStr = map.get("endTime").toString();
    Date startTime = DateUtil.getMyTime(startTimeStr);
    Date endTime = DateUtil.getMyTime(endTimeStr);
    map.put("startTime", startTime);
    map.put("endTime", endTime);
    //添加问卷信息
    int result = questionnaireEntityMapper.addQuestionnaire(map);
    return 1;
  }

  /**
   * 根据问卷id修改问卷信息
   *
   * @param map
   * @return 0:问卷名称已经存在 1:修改成功
   */
  public int modifyQuestionnaireInfo(HashMap<String, Object> map) {
    //判断问卷名称是否存在
    if (map.get("questionName") != null) {
      int userResult = questionnaireEntityMapper.queryExistQuestionnaire(map);
      if (userResult != 0) {
        //问卷名称已经存在
        return 0;
      }
    }
    //修改时间
    Date date = DateUtil.getCreateTime();
    map.put("lastUpdateDate", date);
    //修改人
    map.put("lastUpdatedBy", map.get("lastUpdatedBy"));
    //前台传入的时间戳转换
    String startTimeStr = map.get("startTime").toString();
    String endTimeStr = map.get("endTime").toString();
    Date startTime = DateUtil.getMyTime(startTimeStr);
    Date endTime = DateUtil.getMyTime(endTimeStr);
    map.put("startTime", startTime);
    map.put("endTime", endTime);
    int result = questionnaireEntityMapper.modifyQuestionnaireInfo(map);
    return 1;
  }

  /**
   * 根据问卷id查找问卷状态
   *
   * @param questionId
   * @return 问卷状态
   */
  public String queryQuestionnaireIsStopStatus(String questionId) {
    String status = questionnaireEntityMapper.queryQuestionnaireIsStopStatus(questionId);
    return status;
  }

  /**
   * 根据问卷id查找问卷详细信息
   * @param map
   * @return 问卷详细信息
   */
  //queryQuestionnaireById
  public Map<String, Object> queryQuestionnaireById(HashMap<String, Object> map) {
    Map<String, Object> result = questionnaireEntityMapper.queryQuestionnaireById(map);
    return result;
  }

  /**
   * 取消问卷和项目的关联
   *
   * @param questionId
   * @return
   */
  public int cancelQuestionnaireProject(String questionId) {
    int status = questionnaireEntityMapper.queryQuestionnaireStatusById(questionId);
    //问卷进行中
    if (status == 1) {
      return 0;
    }
    int result = questionnaireEntityMapper.cancelConnectionQuestionnaireProject(questionId);
    return 1;
  }

  /**
   * 建立问卷和项目的关联
   *
   * @param map
   */
  public int addQuestionnaireProject(Map<String, Object> map) {
    int result = questionnaireEntityMapper.addConnectionQuestionnaireProject(map);
    return 1;
  }

  /**
   * 根据问卷id删除问卷
   *
   * @param questionId
   * @return
   */
  public int deleteQuestionnaireInfo(String questionId) {
    int status = questionnaireEntityMapper.queryQuestionnaireStatusById(questionId);
    //问卷进行中
    if (status == 3) {
      int result = questionnaireEntityMapper.deleteByPrimaryKey(questionId);
      return 1;
    }
    return 0;
  }

  /**
   * 修改问卷所属项目
   */
  public int modifyProjectInQuestionnaire(HashMap<String, Object> map) {
    int result = questionnaireEntityMapper.modifyProjectInQuestionnaire(map);
    return 1;
  }

  /**
   * 查询所有问卷的详细信息
   *
   * @param map
   * @return
   */
  public PageInfo queryQuestionnaireInfo(Map<String, Object> map) {
    //分页查询
    PageHelper.startPage(Integer.parseInt(map.get("pageNum").toString()),
      Integer.parseInt(map.get("pageSize").toString()));
    List<Map<String, Object>> mapList = questionnaireEntityMapper.queryAllQuestionnaireList(map);
    PageInfo<Map<String, Object>> objectPageInfo = new PageInfo<>(mapList);
    return objectPageInfo;
  }

  /**
   * 根据问卷名查询和项目id所有问卷不是本项目的问卷
   *
   * @param map
   * @return
   */
  public PageInfo queryQuestionnaireByNameAndProjectid(Map<String, Object> map) {
    //分页查询
    PageHelper.startPage(Integer.parseInt(map.get("pageNum").toString()),
      Integer.parseInt(map.get("pageSize").toString()));
    List<Map<String, Object>> mapList = questionnaireEntityMapper.queryQuestionnaireByNameAndProjectid(map);
    PageInfo<Map<String, Object>> objectPageInfo = new PageInfo<>(mapList);
    return objectPageInfo;
  }

  /**
   * 根据问卷id查询问卷的结束语和短信内容
   *
   * @param map
   * @return
   */
  public Map<String, Object> queryQuestionnaireEndAndSmsContent(HashMap<String, Object> map) {
    Map<String, Object> resultMap = questionnaireEntityMapper.queryQuestContextEndById(map);
    return resultMap;
  }

  /**
   * 根据id修改问卷状态
   *
   * @param map
   * @return
   */
  public int modifyQuestionnaireStatus(HashMap<String, Object> map) {
    int result = questionnaireEntityMapper.modifyQuestionnaireStatus(map);
    return 1;
  }

  //修改问卷全部信息
  public int modifyQuestionnaire(HashMap<String, Object> map) {
    //修改时间
    Date date = DateUtil.getCreateTime();
    map.put("lastUpdateDate", date);
    //修改人
    map.put("lastUpdatedBy", map.get("user"));
    int result = questionnaireEntityMapper.modifyQuestionnaire(map);
    return 1;
  }

  /**
   * 添加发送问卷方式
   */
  public int addSendQuestionnaire(HashMap<String, Object> map) {
    //通过问卷id查询问卷开始结束时间
    //Map<String, Object> questionnaireMap = questionnaireEntityMapper.queryQuestionnaireStartEndTime(map.get
    // ("questionId").toString());
    //问卷开始时间
    //String startTime = questionnaireMap.get("startTime").toString();
    //问卷结束时间
    //String endTime = questionnaireMap.get("endTime").toString();
    //修改时间
    Date date = DateUtil.getCreateTime();
    map.put("lastUpdateDate", date);
    //修改人
    map.put("lastUpdatedBy", map.get("user"));
    //修改问卷状态为进行中、答卷数量0
    map.put("questionStop", "1");
    map.put("answerTotal", "0");
    //短信发送方式
    if (map.get("sendType").equals("0")) {
      //前台传入的发布时间戳转换
      if (map.get("releaseTime").equals("")) {
        map.put("releaseTime", date);
      } else {
        String releaseTimeStr = map.get("releaseTime").toString();
        Date releaseTime = DateUtil.getMyTime(releaseTimeStr);
        map.put("releaseTime", releaseTime);
        //短信发送接口
       /* com.aliyun.dysmsapi20170525.Client client = null;
        try {
          client = ShortMessageConfig.createClient("ACCESS_KEY_ID", "ACCESS_KEY_SECRET");
          SendSmsRequest sendSmsRequest = new SendSmsRequest()
            .setSignName("问卷星链接")
            .setTemplateCode("SMS_154950909")
            .setPhoneNumbers("13775326232")
            .setTemplateParam("{\"code\":\"1234\"}");
          RuntimeOptions runtime = new RuntimeOptions();
          SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
        */
      }
    }
    //邮箱发送方式
    if (map.get("sendType").equals("1")) {
      map.put("releaseTime", date);
      //163邮箱发送,个人电脑授权码：FGHJKFHDCPOJANNF
      // SMTP服务器: smtp.163.com
      try {
        //这里的邮箱是接受者的邮箱，和配置的邮箱不一样，配置的邮箱是发送者的邮箱
        List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("sendInfo");
        //循环发送邮件
        for (Map<String, Object> map1 : list) {
          String emailAddress = map1.get("answerEmail").toString();
          boolean result = emailAddress.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
          //验证邮箱格式
          if (!result) {
            return 0;
          }
        }
        for (Map<String, Object> map1 : list) {
          String emailAddress = map1.get("answerEmail").toString();
          //找到【联系人姓名】字段，替换为联系人姓名
          String emailName = map1.get("answerName").toString();
          String context = (String) map.get("context");
          context = context.replace("联系人姓名", emailName);
          //替换【填写问卷地址】字段，替换为填写问卷地址
          String url = "http://127.0.0.1:8085/pages/previewQuestionnaire.html?id=" + map.get("questionId");
          context = context.replace("【填写问卷地址】", url);
          //发送邮件
          MailUtil.sendMail(emailAddress, (String) map.get("emailTitle"), context);
        }
      } catch (MessagingException e) {
        e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    int result = questionnaireEntityMapper.addSendQuestionnaire(map);
    return 1;
  }

  //保存问卷结束语和短信内容
  public int saveSendQuestionnaire(HashMap<String, Object> map) {
    //修改时间
    Date date = DateUtil.getCreateTime();
    map.put("lastUpdateDate", date);
    //修改人
    map.put("lastUpdatedBy", map.get("user"));
    //修改问卷状态为进行中、答卷数量0
    map.put("questionStop", "1");
    map.put("answerTotal", "0");
    //短信发送方式
    if (map.get("sendType").equals("0")) {
      //前台传入的发布时间戳转换
      if (map.get("releaseTime").equals("")) {
        map.put("releaseTime", date);
      } else {
        String releaseTimeStr = map.get("releaseTime").toString();
        Date releaseTime = DateUtil.getMyTime(releaseTimeStr);
        map.put("releaseTime", releaseTime);
      }
    }
    //邮箱发送方式
    if (map.get("sendType").equals("1")) {
      map.put("releaseTime", date);
    }
    if (map.get("sendType").equals("2")) {
      map.put("releaseTime", date);
    }
    int result = questionnaireEntityMapper.addSendQuestionnaire(map);
    return 1;
  }

  //查询历史问卷
  public List<Map<String, Object>> queryHistoryQuestionnaire(HashMap<String, Object> map) {
    List<Map<String, Object>> mapList = questionnaireEntityMapper.queryHistoryQuestionnaire(map);
    return mapList;
  }

}

